package keyon.tang.service.impl;

import keyon.tang.custom.ShopCustom;
import keyon.tang.dao.ShopCategoryDao;
import keyon.tang.dao.ShopDao;
import keyon.tang.dto.ShopExcution;
import keyon.tang.entity.Shop;
import keyon.tang.entity.ShopCategory;
import keyon.tang.enums.ShopStateEnum;
import keyon.tang.exceptions.ShopException;
import keyon.tang.service.ShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @Author: tangkeyon@gmail.com
 * @Date: 2019/5/10 19:50
 * @Version 1.0
 */

/**
 * 保证事务方法的执行时间尽可能短，不要穿插其他网络操作，RPC/HTTP请求或者剥离到事务方法外部
 * //             不是所有的方法都需要事务，如只有一条修改操作，只读操作不需要事务控制
 */
@Transactional
@Service
public class ShopServiceImpl implements ShopService {
    @Value("${imgFile.path}")
    private String imgFilePath;

    @Autowired
    private ShopDao shopDao;

    @Autowired
    private ShopCategoryDao shopCategoryDao;

    @Override
    public ShopExcution updateShop(ShopCustom shopCustom) {
//        在传入参数不为空的前提下进行
        if (shopCustom != null) {
//            开启事务对数据库的操作，业务逻辑涉及对数据库的查看和修改
            try {
                shopCustom.setCreateTime(new Date());
                shopCustom.setLastEditTime(new Date());

//              根据shopCategoryId获得parentId
                if (shopCustom.getShopCategory() != null) {
                    Long shopCategoryId = shopCustom.getShopCategory().getShopCategoryId();
                    ShopCategory shopCategory = shopCategoryDao.queryShopCategoryById(shopCategoryId);
                    shopCustom.setParentCategory(shopCategory);
                }
//               用户更新了图片
                if (shopCustom.getImgFile() != null) {
//                    删除之前数据库中的图片
                    Shop preShop = shopDao.selectShopById(shopCustom.getShopId());
                    System.out.println("----------->" + preShop.getShopImg());
                    deleteImgFile(preShop.getShopImg());

//                    保存用户新上传的图片
                    saveImgFile(shopCustom, shopCustom.getImgFile());
                }
//                调用dao方法来完成店铺的更新
                Shop shop = new Shop();
                BeanUtils.copyProperties(shopCustom, shop);
                int resultNum = shopDao.updateShop(shop);
                if (resultNum <= 0) {//更新失败
                    return new ShopExcution(ShopStateEnum.INNER_ERROR);
                } else {//更新成功
                    return new ShopExcution(ShopStateEnum.SUCCESS);
                }
            } catch (Exception e) {
                throw new ShopException("inner error" + e.getMessage());
            }


        }
//        判断有没有上传新照片，有的话就将原先的照片替换掉

        return null;
    }

    @Override
    public Shop selectShopById(Integer shopId) {
        return shopDao.selectShopById(shopId);
    }

    @Override
    public ShopExcution addShop(ShopCustom shopCustom) {
//        传入的ShopCustom为空
        if (shopCustom == null) {
            return new ShopExcution(ShopStateEnum.NULL_SHOPID);
        } else {
//            下面的一系列操作为一个事务，用try....catch....抛出运行时异常的方式来实现事务的回滚
            try {
//                为shopCustom的时间字段赋值
                        shopCustom.setEnableStatus(0);
                        shopCustom.setCreateTime(new Date());
                        shopCustom.setLastEditTime(new Date());
//                      通过ShopCustom的ShopCategoryId查到parentId
//                       parentId是一级列表内的id,ShopCategoryId是二级列表内的id，两个保存在同一张表内
//                       传来的是二级列表的id
                        if (shopCustom.getShopCategory() != null) {
                                Long categoryId = shopCustom.getShopCategory().getShopCategoryId();
                                ShopCategory category = shopCategoryDao.queryShopCategoryById(categoryId);
                                ShopCategory parentCategory = new ShopCategory();
                                parentCategory.setParentId(category.getParentId());
                                shopCustom.setParentCategory(parentCategory);
                        }
                                Shop shop = new Shop();
                                BeanUtils.copyProperties(shopCustom, shop);
//                                调用dao的方法来操作数据库
                            int alterNum = shopDao.insertShop(shop);
                             System.out.println("-------------->"+shop.getShopId());
                            if (alterNum <= 0) {
                                throw new ShopException("insertShop error");
                            } else {
//                      向数据库中添加之后返回主键值保存在shopId内
//                      将shopId用作子目录存放上传的文件，
//                      存放完成后更新数据库，为shopImg赋值
                            MultipartFile imgFile = shopCustom.getImgFile();
                            if (imgFile != null) {
                                saveImgFile(shop, imgFile);
                                int inserImgRes = shopDao.updateShop(shop);
                                if(inserImgRes<1)
                                    throw new ShopException("图片创建失败");
                            }

                            return new ShopExcution(ShopStateEnum.PASS);
                        }


            } catch (Exception e) {
                throw new ShopException("inner error" + e.getMessage());
            }
        }
    }

    /**
     * 保存用户上传的图片并将图片的地址设置到shopCustom里
     *
     * @param
     * @param imgFile
     * @throws RuntimeException
     */
    private void saveImgFile(Shop shop,MultipartFile imgFile) throws RuntimeException {
//            判断存放图片的文件夹是否存在
        String fileSavePath = imgFilePath + shop.getShopId();
        File imgDir = new File(fileSavePath);
        if (!imgDir.exists()) {
            imgDir.mkdirs();
        }
//            对上传图片进行重命名
        String imgName = System.currentTimeMillis() + "_" + imgFile.getOriginalFilename();
//            在文件夹下创建出新的文件
        File newFile = new File(fileSavePath, imgName);
        try {
            imgFile.transferTo(newFile);
            shop.setShopImg(fileSavePath + "/" + imgName);
        } catch (IOException e) {
            throw new ShopException("save img error" + e.getMessage());
        }
    }

    private void saveImgFile(ShopCustom shopCustom ,MultipartFile imgFile) throws RuntimeException {
//            判断存放图片的文件夹是否存在
        String fileSavePath = imgFilePath + shopCustom.getShopId();
        File imgDir = new File(fileSavePath);
        if (!imgDir.exists()) {
            imgDir.mkdirs();
        }
//            对上传图片进行重命名
        String imgName = System.currentTimeMillis() + "_" + imgFile.getOriginalFilename();
//            在文件夹下创建出新的文件
        File newFile = new File(fileSavePath, imgName);
        try {
            imgFile.transferTo(newFile);
            shopCustom.setShopImg(fileSavePath + "/" + imgName);
        } catch (IOException e) {
            throw new ShopException("save img error" + e.getMessage());
        }
    }

    /**
     * 从shopCustom获取图片的地址并删除数据库中的图片
     *
     * @param
     */
    private void deleteImgFile(String shopImg) {
        File imgURl = new File(shopImg);
        if (imgURl.exists()) {
            if (imgURl.isDirectory()) {
                File[] imgFiles = imgURl.listFiles();
                for (int i = 0; i < imgFiles.length; i++) {
                    imgFiles[i].delete();
                }

            }
            imgURl.delete();
        }


    }
}






